package com.xframe.xdal.core.autofill.proc;

import cn.hutool.core.convert.Convert;
import com.xframe.xdal.core.autofill.IAutoFillBean;
import com.xframe.xdal.core.autofill.IAutoProc;
import com.xframe.xdal.core.autofill.specification.ICacheKeyGenerate;
import com.xframe.xdal.core.util.XDateUtil;
import com.xframe.xdal.core.util.redis.RedisAccess;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
/**
 * @Description: 自动生成单号
 * @ClassName:  AB20230619001 ER20230619002
 * @Author: xufeng
 * @CreateTime: 2023/6/15
 **/
@Log4j2
public class BillNoCreateProc implements IAutoProc {

    public static final Integer DEF_SIZE = 3;
    public static final String SPLITSG = ",";
    public static final String PADSTR = "0";

    //  BX 4 3
    // BX20240328 0001
    // BX20240328 0002
    @Override
    public Object getVal(IAutoFillBean autoFillBean, Object entity, Object val) {
        // entity  Is IreaBillNo
        // array[0] %billType=1,AB%,%DFG=*,DF% entity.getBillType()
        // ModelID  辅助类名称  -> call createBillNoQZ()
        String key = "";
        String[] array = autoFillBean.getArgs().split(SPLITSG);
        if(entity instanceof ICacheKeyGenerate){
            key = ((ICacheKeyGenerate)entity).getCacheKey();
        }else {
            key = array[0] + XDateUtil.getDate(XDateUtil.YYYYMMDD);
        }
        Integer size =  DEF_SIZE;
        if(array.length == 2){
            size = Convert.toInt(array[1],DEF_SIZE);
        }
        Long billNo = RedisAccess.getSetCmd().incrBy(key,1);
        RedisAccess.getKeyCmd().expire(key,24 * 60 * 60);
        return key + StringUtils.leftPad(billNo.toString(), size, PADSTR);
    }
}
